<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //利用Object.defineProperty  观察对象

      var obj = {
        name: "张三",
        age: 20,
        height: "170cm",
      };

      function observe(obj) {
        //可以把obj变成可控对象
        //把obj里的所有key都收集起来 放在一个数组里
        var keys = [];
        for (var key in obj) {
          keys.push(key);
        }
        // console.log(keys);
        keys.forEach(function (item) {
          var value = obj[item];
          Object.defineProperty(obj, item, {
            configurable: true,
            enumerable: true,
            get: function () {
              console.log("获取属性的时候触发get");
              return value;
            },
            set: function (newValue) {
              console.log("设置对象的时候触发set方法", newValue);
              if (newValue !== value) {
                value = newValue;
              }
            },
          });
        });
      }
      observe(obj); //把对象改成可控对象
      obj.age = 30;
      console.log(obj);
    </script>
  </body>
</html>
